package com.kavin.aidl;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, BIND_AUTO_CREATE); // 多个Activity 绑定服务,MyService不会重复创建,

    }

    private ServiceProxy serviceProxy;

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // ServiceProxy$Stub$Proxy 服务代理对象
            serviceProxy = ServiceProxy.Stub.asInterface(service);
            Log.d("------TAG", "onServiceConnected: " + name.toString());
            Log.d("------TAG", "onServiceConnected: serviceProxy: " + serviceProxy);

            try {
                serviceProxy.registerCallback(bookcallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) { // 远程 remote
            Log.d("------TAG", "onServiceDisconnected: ");
        }
    };

    /**
     * MyService 的 回调
     */
    BookCallBack.Stub bookcallback = new BookCallBack.Stub() {
        @Override
        public void getCount(int count) throws RemoteException {
            Log.d("------TAG", "getCount: " + count);
        }
    };

    public void click(View view) {
        try {
            String string = serviceProxy.setString("client");
            Book book = serviceProxy.setBook(new Book("数学"));
            Log.d("------TAG", "setString: " + string);
            Log.d("------TAG", "setBook: " + book.getName());
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void jump(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceProxy != null) {
            try {
                serviceProxy.unregisterCallback(bookcallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
